package com.kgc.crowd.distributioncrowdcommon.util;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;

import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * 项目名：distribution-crowd-parent
 * 创建人：Junyizm
 * 创建时间：2020/3/26-10:53
 */
public class UploadUtil {

    public static void uploadSingleFile(
            InputStream inputStream,
            String fileName,
            String endpoint,
            String accessKeyId,
            String accessKeySecret,
            String folderName,
            String bucketName
            ){
        try {
            OSS ossClient = new OSSClientBuilder().build(endpoint,accessKeyId,accessKeySecret);
            String objectName = folderName + "/" + fileName;
            ossClient.putObject(bucketName,objectName,inputStream);
            ossClient.shutdown();
        }catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage());
        }
    }

    /**
     * 生成文件名
     * @param originalFileName 原始文件名
     * @return
     */
    public static String generateFileName(String originalFileName) {

        // 截取扩展名部分
        String extensibleName = "";

        if(originalFileName.contains(".")) {
            extensibleName = originalFileName.substring(originalFileName.lastIndexOf("."));
        }
        return UUID.randomUUID().toString().replaceAll("-", "")+extensibleName;
    }

    /**
     * 根据日期生成目录名称
     * @return
     */
    public static String generateDayFolderName() {

        return new SimpleDateFormat("yyyyMMdd").format(new Date());
    }

}
